package ne.aishuyuan.video.view;

import lombok.extern.slf4j.Slf4j;
import ne.aishuyuan.video.bean.Media;
import ne.aishuyuan.video.bean.NetworkMedia;
import ne.aishuyuan.video.bean.PlayMedia;
import ne.aishuyuan.video.service.LoadResourceServiceNoframe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.binding.internal.libvlc_media_player_t;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.media.*;
import uk.co.caprica.vlcj.player.base.*;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * @ClassName: Player
 * @Description: vlcj 播放器
 * @Author: clj
 * @Date: 2021/11/2 16:09
 */
@Slf4j
@EnableScheduling
//@Component
public class PlayerNoFrame  {

	private MediaPlayer mediaPlayer;

	private Media currentMedia;
	//实际播放清单
	private PlayMedia playMedia;
	//固定播放清单
	private PlayMedia fixedPlayMedia;
	//定时播放清单
	private PlayMedia timerPlayMedia;
	//实际播放列表
	private java.util.List<Media> mediaList;
	//固定播放列表
	private List<Media> fixedMediaList;
	//定时播放列表
	private List<Media> timerMediaList;
	private MediaPlayerFactory factory;
	private int playIndex;

	@Value("${download.tempPath}")
	private String tempPath;

	@Autowired
	private LoadResourceServiceNoframe loadResourceService;

	private final List<MediaEventListener> persistentMediaEventListeners = new ArrayList();

	//当前播放标志  0：固定播放 fixed  1：定时播放timer
	private int playRule;

    public PlayerNoFrame() {
		init();
//		config();
    }

	/**
	 * 创建内容面板
	 * @param
	 * @return javax.swing.JPanel
	 */
	private void init() {
		playIndex = 0;
		mediaList = new ArrayList<>();
		fixedMediaList = new ArrayList<>();
		timerMediaList = new ArrayList<>();
		factory = new MediaPlayerFactory();
		mediaPlayer = factory.mediaPlayers().newMediaPlayer();
		libvlc_media_player_t libvlc_media_player_t = mediaPlayer.mediaPlayerInstance();
		LibVlc.libvlc_set_fullscreen(libvlc_media_player_t, 1);
		LibVlc.libvlc_media_player_set_xwindow(libvlc_media_player_t,0xe00003);
		mediaPlayer.events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
			@Override
			public void finished(final MediaPlayer mediaPlayer) {
				mediaPlayer.submit(new Runnable() {
					@Override
					public void run() {
						playIndex ++;
						//根据当前时间加载播放列表
						if (null != timerPlayMedia) {
							LocalDateTime startTime = timerPlayMedia.getPlayStartTime();
							LocalDateTime endTime = timerPlayMedia.getPlayEndTime();
							LocalDateTime date = LocalDateTime.now();
							if (date.isAfter(startTime) && date.isBefore(endTime) && playRule == 0) {
								playMedia = timerPlayMedia;
								playRule = 1;
								mediaList.removeAll(mediaList);
								for (int i =0 ;i < timerMediaList.size();i++) {
									mediaList.add(timerMediaList.get(i));
								}
							} else if ((date.isBefore(startTime) || date.isAfter(endTime)) && playRule == 1) {
								playMedia = fixedPlayMedia;
								playRule = 0;
								mediaList.removeAll(mediaList);
								for (int i =0 ;i < fixedMediaList.size();i++) {
									mediaList.add(fixedMediaList.get(i));
								}
							}
						}

						//顺序播放
						if (playMedia.getPlayPattern().equals("ORDERED")) {
							int index = playIndex;
							int max = mediaList.size();
							if(index + 1 == max) {
								currentMedia= mediaList.get(0);
								playIndex = -1;
							}
							else
							{
								currentMedia = mediaList.get(index + 1);
							}
						} else {
							int index = playIndex;
							int max = mediaList.size();
							//排除当前播放，随机播放其他资源
							Random random = new Random();
							int intIndex = random.nextInt(max);
							while (index == intIndex) {
								intIndex = random.nextInt(max);
							}
							currentMedia = mediaList.get(intIndex);
						}
						//播放
						//随机播放
						String url = currentMedia.getUrl();
						//本地播放
						if (currentMedia.getPlayType().equals("LOCAL_PLAY")) {
							url = currentMedia.getPath() + File.separator + url.substring(url.lastIndexOf("/"));
						}
//						long playTime = currentMedia.getDuration();
						long playTime = 5l;
						log.debug("自动切换>>>>>>>>>>>>>>>>>>>>>>>当前播放路径，{}，播放时长，{}",url,playTime);
						if (currentMedia.getType().equals("VIDEO")) {
							mediaPlayer.media().play(url);
							if (currentMedia.getDuration() == 0) {
								mediaPlayer.media().play(url);
							} else {
								mediaPlayer.media().play(url, "run-time="+playTime);
							}
						} else {
							if (currentMedia.getDuration() == 0) {
								mediaPlayer.media().play(url);
							} else {
								mediaPlayer.media().play(url, "run-time="+playTime);
							}
						}
					}
				});
			}

			@Override
			public void playing(final MediaPlayer mediaPlayer) {
				mediaPlayer.submit(new Runnable() {
					@Override
					public void run() {
//						mediaPlayer.release();
//						mediaPlayer.controls().start();
					}
				});
			}
		});

		mediaPlayer.events().addMediaEventListener(new MediaEventListener() {
			@Override
			public void mediaMetaChanged(uk.co.caprica.vlcj.media.Media media, Meta meta) {

			}

			@Override
			public void mediaSubItemAdded(uk.co.caprica.vlcj.media.Media media, MediaRef mediaRef) {

			}

			@Override
			public void mediaDurationChanged(uk.co.caprica.vlcj.media.Media media, long l) {


			}

			@Override
			public void mediaParsedChanged(uk.co.caprica.vlcj.media.Media media, MediaParsedStatus mediaParsedStatus) {

			}

			@Override
			public void mediaFreed(uk.co.caprica.vlcj.media.Media media, MediaRef mediaRef) {

			}
			@Override
			public void mediaStateChanged(uk.co.caprica.vlcj.media.Media media, State state) {
				System.out.println();

			}

			@Override
			public void mediaSubItemTreeAdded(uk.co.caprica.vlcj.media.Media media, MediaRef mediaRef) {
				System.out.println();

			}

			@Override
			public void mediaThumbnailGenerated(uk.co.caprica.vlcj.media.Media media, Picture picture) {
				System.out.println();

			}
		});
    }

    /**
     * 加载资源
     * @param []
     * @return void
     */
    public void  load() {
		new Thread(() -> {
			NetworkMedia networkMedia =  loadResourceService.loadMedia(mediaList,fixedMediaList,timerMediaList);
			playMedia = networkMedia.getPlayMedia();
			fixedPlayMedia = networkMedia.getFixedPlayMedia();
			timerPlayMedia = networkMedia.getTimerPlayMedia();
			currentMedia  = playMedia.getResourceVos().get(0);
			if (mediaPlayer.media() != null) {
				Iterator var1 = this.persistentMediaEventListeners.iterator();
				while(var1.hasNext()) {
					MediaEventListener listener = (MediaEventListener)var1.next();
					mediaPlayer.media().events().addMediaEventListener(listener);
				}
			}
			mediaPlayer.media().play(currentMedia.getUrl(),"run-time="+5);

		}).start();

	}

    /**
     * 装饰配置
     */
    private void config() {
		//logo
		Logo logo = Logo.logo()
				.file("E:\\resource\\vlcj-logo.png")
				.position(LogoPosition.TOP_RIGHT)
				.opacity(0.5f)
				.enable();
		logo.apply(mediaPlayer);
	}
	//	@Scheduled(cron = "0/5 * * * * ?")
	//或直接指定时间间隔，例如：5秒
/*	@Scheduled(fixedRate=7200000)
	private void configureTasks() {
		log.info(">>>>>>>>>>>>>>>>>>>>>>>>定时拉取播放列表");
		load();
	}*/
}
